package com.lez.coroutine02

import kotlinx.coroutines.*
import org.junit.Test

class Coroutine02 {

    //如果任务超时没执行完 就取消，用withTimeout
    @Test
    fun `test deal with timeout`() = runBlocking {
        withTimeout(1300){
            repeat(1000){ i->
                println("job,i'm sleeping $i")
                delay(500)
            }
        }
    }
    //如果任务超时没执行完 就取消，用withTimeout,并返回个默认值,就不会抛出异常
    @Test
    fun `test deal with timeout return null`() = runBlocking {
        val result = withTimeoutOrNull(1300){
            repeat(1000){ i->
                println("job,i'm sleeping $i")
                delay(500)
            }
            "Normal Value."
        } ?: "Jack"
        println("result is $result")
    }

    //CPU密集型任务取消,,isActive
    @Test
    fun `test cancel cpu task by isActive`() = runBlocking{
        var startTime = System.currentTimeMillis()
        var job = launch(Dispatchers.Default) {
            var i = 0
            var nextPrintlnTime = startTime
            while(i < 5 && isActive){
               if(System.currentTimeMillis() > nextPrintlnTime){
                   println("job:i`m sleeping .. ${i++}")
                   nextPrintlnTime += 500
               }
            }
        }
        delay(1300)
        println("main i`m tired of waiting! ")
        job.cancel()
        println("main: Now I can quit.")

    }
}